<?php

namespace app\xiaohongshu\controller;

use addons\qcloudsms\library\SmsSingleSender;
use addons\qcloudsms\Qcloudsms;
use app\admin\model\Codes;

use app\admin\model\xiaohongshu\User;
use app\common\controller\Api;
use app\common\library\Sms;
use app\common\library\Token;
use app\common\library\XiaohongshuAuth;


class Login extends Api
{
    
    protected $noNeedLogin = ['verify','index','reg','sms','password'];



    public function password()
    {
        // Retrieve login parameters
        $mobile = $this->request->param('mobile');
        $password = $this->request->param('password');

        // Validate input
        if (empty($mobile)) {
            return $this->error('手机号码不能为空');
        }

        if (empty($password)) {
            return $this->error('密码不能为空');
        }

        // Find user by mobile
        $user = User::where('mobile', $mobile)->find();
        if (!$user) {
            return $this->error('用户不存在');
        }

        // Check password
        if ($user->password !== md5($password)) {
            return $this->error('密码错误');
        }
     
        // Generate and store token
        $user->token = md5(uniqid($user->id . time(), true));
        $user->save();

        Token::set($user->token, $user->id,36000000);

        return $this->success('登录成功', ['token' => $user->token]);
    }

    public function sms()
    {


        // Retrieve login parameters
        $mobile = $this->request->param('mobile');
        $code = $this->request->param('code');

        // Validate input
        if (empty($mobile)) {
            return $this->error('手机号码不能为空');
        }



        if (empty($code)) {
            return $this->error('验证码不能为空');
        }

        $re = Sms::check($mobile, $code);
        if(!$re){
            return $this->error('验证码不正确');
        }

        // Check if user exists
        $user = User::where('mobile', $mobile)->find();
        if (!$user) {
            return $this->error('用户不存在');
        }

        // Verify OTP code
        $codeRecord = Codes::where('mobile', $mobile)->where('code', $otp)->find();
        if (!$codeRecord) {
            return $this->error('验证码无效或已过期');
        }

        // OTP verified, generate and store token
        $user->token = md5(uniqid($user->id . time(), true));
        $user->save();

        Token::set($user->token, $user->id,36000000);

        // Mark OTP code as used
        $codeRecord->is_used = true;
        $codeRecord->save();

        return $this->success('登录成功', ['token' => $user->token]);
    }

    public function reg(){
        // 获取注册信息
        $nickname = $this->request->param('nickname');
        $password = $this->request->param('password');
        $company = $this->request->param('company');
        $mobile = $this->request->param('mobile');
        $code = $this->request->param('code');

// 验证必填字段并分别提示
        if (empty($nickname)) {
            return $this->error('昵称不能为空');
        }

        if (empty($password)) {
            return $this->error('密码不能为空');
        }

        if (empty($mobile)) {
            return $this->error('手机号码不能为空');
        }

        if (empty($code)) {
            return $this->error('验证码不能为空');
        }


        // 验证手机号码格式
        if(!preg_match("/^1[3-9]\d{9}$/", $mobile)){
            return $this->error('手机号码格式不正确');
        }


        // 验证手机号是否已存在
        $exists = \app\admin\model\xiaohongshu\User::where('mobile', $mobile)->find();
        if($exists){
            return $this->error('该手机号已注册');
        }
        
        // 验证昵称是否已存在
        $exists = \app\admin\model\User::where('nickname', $nickname)->find();
        if($exists){
            return $this->error('昵称已存在');
        }


        $re = Sms::check($mobile, $code);
        if(!$re){
            return $this->error('验证码不正确');
        }
        // 创建新用户
        $user = new User();
        $user->nickname = $nickname;
        $user->password = md5($password);
        $user->company = $company;
        $user->mobile = $mobile;
        $user->createtime = time();
        $user->score = 50;
        if($user->save()){
            return $this->success('注册成功');
        }else{
            return $this->error('注册失败');
        }
    }
    
    public function index()
    {



    }
    // 验证code并返回token
    public function verify()
    {
        // 从请求中获取code
        $code = $this->request->param('code');
      
        // 检查code是否存在
        $codeRecord = Codes::where('code', $code)->find();
        
        if (!$codeRecord) {
            return json(['error' => '无效的code'], 400);
        }

        // // 检查token是否已激活
        // if ($codeRecord->is_activated) {
        //     return json(['error' => 'token已激活'], 400);
        // }

        // 生成新的token (这里只是一个示例，你可以使用更安全的方式生成token)
        // $newToken = md5(uniqid($code, true));

        // 更新数据库中的token和激活状态
        // $codeRecord->token = $newToken;
        $codeRecord->is_activated = true;
        $codeRecord->last_activated_at = date('Y-m-d H:i:s');
        $codeRecord->save();

        // // 返回生成的token
        return  $this->success('请求成功',['token' => $codeRecord->token]);
    }
}
